<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Foundation\Facades\Log;
use App\Model\Auth\User;
use App\Service\Auth\UserService;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\WebSocketServer\Context;
use Hyperf\WebSocketServer\Security;
use App\Foundation\Utils\JWT;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;


/**
 * WebSocket鉴权中间件
 * Class WsMiddleware
 * @package App\Middleware
 */
class WsMiddleware implements MiddlewareInterface
{


    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var JWT
     */
    protected $jwt;

    public function __construct(ContainerInterface $container, RequestInterface $request, JWT $jwt)
    {
        $this->container = $container;
        $this->request = $request;
        $this->jwt = $jwt;
    }

    /**
     * WebSocket鉴权中间件
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Throwable
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $isValidToken = false;
        $token = $request->getHeaderLine(Security::SEC_WEBSOCKET_PROTOCOL) ?? '';
        if (!empty($token)) {
            try {
                if ($this->jwt->checkToken($token)) {
                    $isValidToken = true;
                }
            } catch (\Throwable $e) {

            }
        }
        if (!empty($request->getQueryParams()['is_reconnection'])) {
            Context::set('is_reconnection', true);
        }
        if ($isValidToken) {
            $jwtData = $this->jwt->getParserData($token);
            $userInfo = UserService::getInstance()->getByUid($jwtData['uid']);
            Context::set('user_info', $userInfo);
        } else {
            Log::debug()->info('user info error');
            Context::set('user_info', null);
        }
        return $handler->handle($request);
    }
}
